package com.platform.common.mybatis.handler;

import com.platform.common.web.utils.UserContext;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.reflection.MetaObject;
import java.time.LocalDateTime;

@Api(tags = "使用mybatis-plus做自动填充，配置自动填充的组件MyMetaObjectHandler:" +
        "1.实体类中公共字段，添加@TableField注解,springboot底层帮我们做好了自动配置，我们只需要根据需求去添加组件即可。")
public class MyMetaObjectHandler implements MetaObjectHandler {

    @ApiOperation("新增填充创建时间、操作人")
    @Override
    public void insertFill(MetaObject metaObject) {
//        this.setFieldValByName("gmtCreate",new Date(),metaObject);
//        this.setFieldValByName("gmtModified",new Date(),metaObject);
        this.strictInsertFill(metaObject,"createTime",()-> LocalDateTime.now(), LocalDateTime.class);
        this.strictUpdateFill(metaObject,"updateTime",()->LocalDateTime.now(),LocalDateTime.class);
        this.strictInsertFill(metaObject, "createBy", () -> UserContext.getCurrentUserId(), Long.class);
        this.strictUpdateFill(metaObject, "updateBy", () -> UserContext.getCurrentUserId(), Long.class);
    }

    @ApiOperation("更新填充更新时间、操作人")
    @Override
    public void updateFill(MetaObject metaObject) {
//        this.setFieldValByName("gmtModified",new Date(),metaObject);
        this.strictUpdateFill(metaObject, "updateBy", () -> UserContext.getCurrentUserId(), Long.class);
        this.strictUpdateFill(metaObject,"updateTime",()->LocalDateTime.now(),LocalDateTime.class);
    }
}
